package com.example.medicine.controller;




import com.example.medicine.Bean.yonghu;
import com.example.medicine.Mapper.TeamMapper;
import com.example.medicine.Mapper.yonghuMapper;
import com.example.medicine.md5_guid.md5_guid;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.poi.ss.usermodel.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;


import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import static org.apache.commons.codec.digest.DigestUtils.md5Hex;

@RestController
@RequestMapping("/user")
public class userController {
    private static final String UPLOADED_FOLDER = System.getProperty("user.dir") +
            "/src/main/resources/static/uploadImages/";
    @Autowired
    yonghuMapper yonghuMapper;
    @Autowired
    TeamMapper teamMapper;

    /**
     * 接收yonghuList请求，返回数据库的yonghu表内的所有内容，格式为json
     * @return
     */
    @GetMapping("/")
    public List<yonghu> getuserList(){
        return yonghuMapper.getAll();
    }

    /**
     * 接收insertyonghu请求，向yonghu中插入内容
     */
    @PostMapping("/")
    public void insertuser(@RequestParam("user") String userJson,
                           @RequestParam(value = "smallfile", required = false) MultipartFile smallfile)throws IOException {
        String smallfileName = null;
        ObjectMapper objectMapper = new ObjectMapper();
        yonghu user = objectMapper.readValue(userJson, yonghu.class);
        String md5Pwd=new md5_guid(user.getPassword()).md5();
        user.setPassword(md5Pwd);
        if (smallfile != null && !smallfile.isEmpty())
             smallfileName=fileLoad(smallfile);
        user.setImage(smallfileName);
        yonghuMapper.insert2(user);
    }
    /**
     * 接收updateyonghu请求，根据ID值更新yonghu内容
     */
    @PutMapping("/")
    public void updateuser(@RequestParam("user") String userJson,
                           @RequestParam(value = "smallfile", required = false) MultipartFile smallfile) throws IOException {
        String smallfileName = null;
        ObjectMapper objectMapper = new ObjectMapper();
        yonghu user = objectMapper.readValue(userJson, yonghu.class);
        String md5Pwd=new md5_guid(user.getPassword()).md5();
        user.setPassword(md5Pwd);
        if (smallfile != null && !smallfile.isEmpty())
            smallfileName=fileLoad(smallfile);
        user.setImage(smallfileName);
        yonghuMapper.update(user);
        if (smallfile != null && !smallfile.isEmpty())
            yonghuMapper.updateImage(user);
    }
    @PostMapping("/batch/")
    public ResponseEntity<String> insertBatchUser(@RequestParam("file") MultipartFile file) {
        try {
            // 校验文件类型，只接受 .xls 和 .xlsx 格式的文件
            if (!file.getOriginalFilename().endsWith(".xls") && !file.getOriginalFilename().endsWith(".xlsx")) {
                return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Unsupported file format. Please upload an Excel file.");
            }

            List<yonghu> userList = new ArrayList<>();
            // 使用 Apache POI 解析 Excel 文件并提取数据
            Workbook workbook = WorkbookFactory.create(file.getInputStream());
            Sheet sheet = workbook.getSheetAt(0);

            for (Row row : sheet) {
                if (row.getRowNum() == 0) { // 跳过表头行
                    continue;
                }
                yonghu user = new yonghu();
                for(int i=0;i<=8;++i){
                    String value=null;
                    Cell cell= row.getCell(i);
                    if(cell!=null){
                        CellType cellType=cell.getCellType();
                        value = switch (cellType) {
                            case STRING ->
                                // 处理字符串类型的单元格
                                    cell.getStringCellValue();
                            case NUMERIC ->
                                // 处理数值类型的单元格
                                    String.valueOf((int)cell.getNumericCellValue());
                            default -> null;
                        };
                    }
                    switch (i) {
                        case 0 -> user.setUserid(value);
                        case 1 -> user.setUsername(value);
                        case 2 -> user.setPassword(md5Hex(value));
//                        case 2 -> user.setPassword(value);
                        case 3 -> user.setTeamName(value);
                        case 4 -> user.setType(value);
                        case 5 -> user.setTel(value);
                        case 6 -> user.setEmail(value);
                        case 7 -> user.setCompany(value);
                        case 8 -> user.setAddr(value);
                    }

                }

                user.setTeamID(teamMapper.getid(user.getTeamName()));
                user.setCreateuser("admin");System.out.println(user);
                userList.add(user);
            }
            // 将数据批量插入数据库
            if (!userList.isEmpty()) {
                yonghuMapper.batchInsertUser(userList);
                System.out.println("成功！");
            }
            return ResponseEntity.ok().body("{\"message\": \"文件提交成功!\"}");
        } catch (Exception e) {
            e.printStackTrace(); // 添加错误日志
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("{\"message\": \"发生错误！请联系管理员！\"}");
        }
    }
    @PutMapping ("/updatepassword/")
    public void deleteuser(@RequestBody yonghu user){
        String md5Pwd=new md5_guid(user.getPassword()).md5();
        user.setPassword(md5Pwd);
        yonghuMapper.updatepassword(user);
    }
    @DeleteMapping("/{userid}")
    public void deleteuser(@PathVariable String userid){
        yonghuMapper.deleteById(userid);
    }
    private String fileLoad(MultipartFile file) throws IOException {
        String fname = file.getOriginalFilename();    //获取原始的文件名
        //用UUID作为新文件名，扩展名不变  避免同名覆盖
        String newName = UUID.randomUUID()+ "." + fname.substring(fname.lastIndexOf(".")+1);
        File dest_file = new File( UPLOADED_FOLDER + newName );
        System.out.println(UPLOADED_FOLDER);
        file.transferTo(dest_file);
        return newName;
    }
}
